package com.srwl.mytx.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MultiPointItem;
import com.amap.api.maps.model.MultiPointOverlay;
import com.amap.api.maps.model.MultiPointOverlayOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.AnimationSet;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.MainActivity;
import com.srwl.mytx.activity.PublishTopicActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.activity.TopicListActivity;
import com.srwl.mytx.activity.TopicSearchActivity;
import com.srwl.mytx.adapter.BottomTopicListAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.BottomTopicListV1;
import com.srwl.mytx.widget.ContactListView_v1;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jzvd.JzvdStd;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by dahai2070 on 2016/8/23 0023.
 */
public class GaoDeMapFragment extends BaseFragment implements View.OnClickListener, AMap.OnMyLocationChangeListener, AMapLocationListener, PermissionsUtils.IPermissionsResult {
    private static final String TAG = GaoDeMapFragment.class.getSimpleName();
    public static final int REQUEST_CODE_TO_TOPIC_DETAIL = 1;
    public static final int REQUEST_CODE_TO_TOPIC_DETAIL_FROM_PUSH_MESSAGE = 2;
    private static final int MAKER_HEIGHT = 25;//单位dp
    private ProgressBar progressBar;
    private MapView mapView = null;
    public AMap aMap = null;
    private UiSettings mUiSettings;

    private DrawerLayout mDrawerLayout;
    private ContactListView_v1 contactListView;
    private RecyclerView rv_search;
    private ImageButton btnMapStatus;
    private ImageButton btn_publish;
    private ImageButton btn_3dSwitch;
    private ImageButton btn_showContact;
    private ImageButton btn_search;
    private ImageView btn_topicList;
    private ConstraintLayout clZoomContainer;
    private boolean hidden;
    private long startTime = 0;
    private int changeCount = 0;
    private float lastY = 0;
    private float lastX = 0;
    private boolean bol_directionDown = true;
    private boolean bol_directionRight = true;
    boolean bol_firstSlide = true;

    boolean bol_hasClear = false;//标记单次屏幕事件中是否已经清除了地图覆盖物
    boolean bol_needNearbySearch = false;//标记是否需要附近搜索
    private MyLocationStyle myLocationStyle;
    private boolean showSearchResult;
    private boolean firstLocationSuccess;
    //  private AMapLocationClient mLocationClient;
    private final static int SLIDE_CHANGE_DIRECTION_THRESHOLD = 15;//滑动换向检测阈值
    private boolean isNearbySearching;
    private LatLng lastCameraCenter;//上一次地图中心点
    private int lastSearchRadius;//上一次搜索的半径
    private float lastZoom;//上一次的地图缩放级别
    private boolean followMove = true;
    private MainActivity.ChangeFragmentListener listener;
    private List<Topic> resultsList = new ArrayList<>();//搜索主题集合
    private List<Topic> pushTopicList = new ArrayList<>();//推送主题集合
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    //为了让收到的推送主题，在当前页面没有被隐藏的情况下，均匀的显示给用户，
    private int postDelay = 10000;
    //标记是否在继续循环显示
    private boolean isContinue;
    private Handler handler = new Handler();
    private Runnable showPushTopic = new Runnable() {
        @Override
        public void run() {
            if (pushTopicList.size() != 0) {
                Topic remove = pushTopicList.remove(0);

                showSingleMarker(remove);
            }

            if (pushTopicList.size() != 0 && !hidden) {
                isContinue = true;
                handler.postDelayed(showPushTopic, postDelay);
            } else {
                isContinue = false;
            }
        }
    };
    private List<Marker> topicMarkerList = new ArrayList<>();
    private List<Marker> userMarkerList = new ArrayList<>();

    private Integer lastSelectPosition;
    private float zoom;
    //    private BottomTopicList bottomTopicList;
    private BottomTopicListV1 bottomTopicListV1;
    private boolean markerAnimoteOuting;//标记 marker 正在执行消失动画
    private ImageView ivSearch;
    private int tryLocationCount;//尝试定位的次数
    private GaodeLocationClient locationClient;

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // SDKInitializer.initialize(getActivity().getApplicationContext());
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        initContactListView(view);
        progressBar = view.findViewById(R.id.progress_bar);
        mapView = view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        mDrawerLayout = view.findViewById(R.id.drawer_layout);
        initDrawerLayout();
        btnMapStatus = view.findViewById(R.id.btn_map_status);
        btn_3dSwitch = view.findViewById(R.id.btn_3d_switch);
        btn_showContact = view.findViewById(R.id.btn_show_contact);
        btn_publish = view.findViewById(R.id.btn_publish);
        rv_search = view.findViewById(R.id.rl_search);
        btn_search = view.findViewById(R.id.btn_search);
        clZoomContainer = view.findViewById(R.id.cl_zoom_container);
        view.findViewById(R.id.iv_scale_add).setOnClickListener(this);
        view.findViewById(R.id.iv_scale_reduce).setOnClickListener(this);
        ivSearch = view.findViewById(R.id.iv_search);
        btnMapStatus.setOnClickListener(this);
        btn_publish.setOnClickListener(this);
        btn_3dSwitch.setOnClickListener(this);
        btn_showContact.setOnClickListener(this);
        //btn_search.setOnClickListener(this);
        btn_topicList = view.findViewById(R.id.iv_topic_list);
        btn_topicList.setOnClickListener(this);
        ivSearch.setOnClickListener(this);
        registerBroadcastReceiver();
        // showGuide();
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // aMapView = (com.amap.api.maps.MapView) view.findViewById(R.id.aMapView);
        //  aMapView.onCreate(savedInstanceState);
        initLocation();

// String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//10.0 须请求后台定位权限
            permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.ACCESS_BACKGROUND_LOCATION};
        } else {
            permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE
            };
        }

        PermissionsUtils.getInstance().checkPermissions(this, permissions, this);
    }


    void initDrawerLayout() {

        mDrawerLayout.setScrimColor(Color.TRANSPARENT);
        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {

            }

            @Override
            public void onDrawerOpened(@NonNull View view) {
                hideSoftKeyboard();
                /*searchView.setVisibility(View.GONE);
                searchView.onActionViewCollapsed();*/
                //closeSearchView();
            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
                //searchView.setVisibility(View.VISIBLE);

            }

            @Override
            public void onDrawerStateChanged(int i) {

            }
        });
    }


    private void initContactListView(View view) {

        contactListView = view.findViewById(R.id.contact_list_view);
        contactListView.init(Helper.getInstance().getContactList());
        contactListView.setListener(new ContactListView_v1.InteractionListener() {
            @Override
            public void onContactDelete() {
//                ((MainActivity) getActivity()).updateUnreadLabel();//更新未读红点
            }

            @Override
            public void addContact() {
                mDrawerLayout.closeDrawer(contactListView);
                // searchTextView.setHint("输入手机号搜索联系人");
                // searchTextView.setHintTextColor(getResources().getColor(R.color.placeholder));
                // searchView.setIconified(false);
            }
        });
        IMSClientBootstrap.getInstance().addLoginListenerList(new IMSClientBootstrap.LoginListener() {
            @Override
            public void onRestLoginSuccess() {
                contactListView.refresh(Helper.getInstance().getContactList());
            }
        });
    }


    private void initLocation() {
//        locationClient = new GaodeLocationClient(getActivity());
//        locationClient.setLocationListener(new GaodeLocationClient.LocationListener() {
//            @Override
//            public void locationSuccess(AMapLocation location) {
//                double latitude = location.getLatitude();//获取纬度
//                double longitude = location.getLongitude();//获取经度
//                location(new LatLng(latitude, longitude));
//                com.srwl.mytx.domain.LatLng locationLatLon = new com.srwl.mytx.domain.LatLng(latitude, longitude);
//                if (firstLocationSuccess) {
//                    firstLocationSuccess = false;
//                    if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
//                        autoSearchWithTempUser(locationLatLon);
//                    } else {
//                        autoSearch(locationLatLon);
//                    }
//                }
//            }
//        });
        aMap = mapView.getMap();
        mUiSettings = aMap.getUiSettings();

        //设置不显示指南针
        mUiSettings.setCompassEnabled(false);
        //显示缩放按钮
        mUiSettings.setZoomControlsEnabled(false);
        //显示定位按键
        mUiSettings.setMyLocationButtonEnabled(false);
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//LOCATION_TYPE_SHOW 定位一次，不移动地图 LOCATION_TYPE_LOCATE:定位一次 ，地图移动到定位地点 LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER:连续定位，图标转动，
        myLocationStyle.showMyLocation(true);
        myLocationStyle.anchor(0.5f, 0.5f);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.strokeWidth(1f);
        myLocationStyle.interval(5000);//连续定位模式下的定位间隔时间
        aMap.setMyLocationStyle(myLocationStyle);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);

        //设置缩放级别
        aMap.animateCamera(CameraUpdateFactory.zoomTo(17));
        //设置地图倾斜度
        aMap.animateCamera(CameraUpdateFactory.changeTilt(30));
        aMap.setOnMyLocationChangeListener(this);
        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                //用户拖动地图后，不再跟随移动，直到用户点击定位按钮
                followMove = false;
                if (!followMove) {
                    if (myLocationStyle.getMyLocationType() != MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER) {
                        //mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW));
                        btnMapStatus.setBackgroundResource(R.drawable.tx_map_location);
                        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));
                        //btn_trackQuery.setVisibility(View.VISIBLE);
                        //btnMapStatus.setVisibility(View.INVISIBLE);
                    } else {
                        aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER));
                    }

                }

                float currentX = motionEvent.getRawX();
                float currentY = motionEvent.getRawY();
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //如果拖动地图的时候，循环在执行，那么中断循环
                        if (isContinue) {
                            handler.removeCallbacks(showPushTopic);
                        }
                        startTime = motionEvent.getDownTime();
                        bol_hasClear = false;
                        bol_needNearbySearch = false;
                        break;

                    case MotionEvent.ACTION_MOVE:
                        bol_needNearbySearch = true;
                        if (bol_firstSlide) {//首次进入滑动状态，设置X、Y方向参考点
                            bol_firstSlide = false;
                            lastX = currentX;
                            lastY = currentY;
                            return;
                        }
                        //检测X方向的滑动换向
                        if (currentX - lastX > 0) {//此刻向右滑动
                            if (!bol_directionRight) {//发生换向，重置参考点
                                if (currentX - lastX > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    //  Log.d(TAG, "onTouch: 向右换向" + changeCount);
                                }
                                //   lastX = currentX;
                            }
                            //设置当前为向右滑动
                            bol_directionRight = true;

                        } else if (currentX - lastX < 0) {//此刻向左边滑动

                            if (bol_directionRight) {//发生换向，重置参考点
                                if (Math.abs(currentX - lastX) > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    //  Log.d(TAG, "onTouch: 向左换向" + changeCount);
                                }
                                // lastX = currentX;
                            }
                            //设置当前为向左滑动
                            bol_directionRight = false;
                        }

                        //检测Y方向的滑动换向

                        if (currentY - lastY > 0) {//此刻向下滑动
                            if (!bol_directionDown) {//发生换向，重置参考点
                                if (currentY - lastY > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    // Log.d(TAG, "onTouch: 向下换向" + changeCount);
                                }
                                // lastY = currentY;
                            }
                            //设置当前为向下滑动
                            bol_directionDown = true;

                        } else if (currentY - lastY < 0) {//此刻向上边滑动

                            if (bol_directionDown) {//发生换向，重置参考点
                                if (Math.abs(currentY - lastY) > SLIDE_CHANGE_DIRECTION_THRESHOLD) {//滑动距离超过阈值，判定为已经换向
                                    changeCount += 1;
                                    //  Log.d(TAG, "onTouch: 向上换向" + changeCount);
                                }
                                // lastY = currentY;
                            }
                            //设置当前为向上滑动
                            bol_directionDown = false;
                        }
                        lastX = currentX;
                        lastY = currentY;
                        long currentTime = motionEvent.getDownTime();
                        if (changeCount >= 3 && !bol_hasClear && currentTime - startTime < 1500) {
                            bol_hasClear = true;
                            //检测到在晃动地图，清空地图上的附加物
                            Log.d(TAG, "onTouch:检测到在晃动地图，清空地图上的附加物 ");
                            //清空marker的同时，也需要把数据集清空
                            resultsList.clear();


                            for (Marker marker : userMarkerList) {
                                if (marker.isVisible()) {
                                    markerHideAnimation(marker);
                                } else {
                                    marker.destroy();
                                }
                            }


                            for (int i = 0; i < topicMarkerList.size(); i++) {
                                Marker marker = topicMarkerList.get(i);
                                if (marker.isVisible()) {
                                    markerHideAnimation(marker);
                                } else {
                                    marker.destroy();
                                }
                            }
                            userMarkerList.clear();
                            topicMarkerList.clear();
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        if (isContinue) {
                            handler.postDelayed(showPushTopic, postDelay);
                        }

                        if (bol_hasClear) {
                            bol_needNearbySearch = false;
                        } else {
                            bol_needNearbySearch = true;
                        }

                        bol_hasClear = false;
                        bol_firstSlide = true;
                        lastX = 0;
                        lastY = 0;
                        changeCount = 0;

                }
            }
        });

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                //  Log.d(TAG, "onCameraChangeFinish: 地图移动了，，，，，");
                LatLng target = cameraPosition.target;
                zoom = cameraPosition.zoom;
                if (lastCameraCenter == null) {
                    lastCameraCenter = target;
                    return;
                }
                //int searchRadius = getSearchRadius();

                if (!bol_needNearbySearch) {
                    Log.d(TAG, "onCameraChangeFinish: 该次地图移动不需要做附近搜索");
                    return;
                }
                bol_needNearbySearch = false;//消费掉最近一次的屏幕触摸事件
                //Log.d(TAG, "搜索半径为searchDistance:" + searchRadius + "  zoom:" + zoom + " scalePerPixel: " + aMap.getScalePerPixel() + "  screenWidth:" + screenWidth);
                Point currentCenterPoint = aMap.getProjection().toScreenLocation(target);
                //获取的屏幕point是以地图的左上位置（零点）为参考点，
                Point lastCenterPoint = aMap.getProjection().toScreenLocation(lastCameraCenter);

                Log.d(TAG, "onCameraChangeFinish: 当前缩放层级 :" + zoom + "lastZoom" + lastZoom);
                if (Math.abs(zoom - lastZoom) >= 0.5) {
                    Log.d(TAG, "onCameraChangeFinish: 缩放层级改变，开始附近搜索");
                    nearbySearch(currentCenterPoint);

                } else if (Math.abs(currentCenterPoint.x - lastCenterPoint.x) <= currentCenterPoint.x * 2
                        && Math.abs(currentCenterPoint.y - lastCenterPoint.y) <= currentCenterPoint.y * 2) { //判断当前屏幕显示区域和上一次是否有重叠，如果有重叠，计算未重叠部分，作为搜索区域
                    List<com.srwl.mytx.domain.LatLng> pointList = new ArrayList<>();

                    if (currentCenterPoint.x - lastCenterPoint.x > 0) {
                        int scrollX = currentCenterPoint.x - lastCenterPoint.x;//x滑动的距离
                        int endX = currentCenterPoint.x * 2; //未查询区域消的结束点X坐标
                        int scrollY = Math.abs(currentCenterPoint.y - lastCenterPoint.y);//Y方向滑动距离
                        int endY = currentCenterPoint.y * 2;//未查询取消结束点Y坐标
                        int focalX = endX - scrollX; //焦点X坐标
                        if (currentCenterPoint.y - lastCenterPoint.y > 0) {
                            Log.d(TAG, "onCameraChangeFinish: 地图向右、向下滑动");

                            int focalY = endY - scrollY;// 焦点Y坐标
                            //从焦点开始，顺时针转动，确定6个点
                            Point point1 = new Point(focalX, focalY);//交点
                            Point point2 = new Point(focalX, 0);
                            Point point3 = new Point(endX, 0);
                            Point point4 = new Point(endX, endY);
                            Point point5 = new Point(0, endY);
                            Point point6 = new Point(0, focalY);

                            genPointList(pointList, point1, point2, point3, point4, point5, point6);

                        } else {
                            Log.d(TAG, "onCameraChangeFinish: 地图向右、向上滑动");
                            int focalY = scrollY;
                            //从焦点开始，顺时针转动，确定6个点
                            Point point1 = new Point(focalX, focalY);//交点
                            Point point2 = new Point(0, focalY);//
                            Point point3 = new Point(0, 0);
                            Point point4 = new Point(0, endY);
                            Point point5 = new Point(endX, endY);
                            Point point6 = new Point(focalX, endY);

                            genPointList(pointList, point1, point2, point3, point4, point5, point6);
                        }

                    } else {
                        int scrollX = Math.abs(currentCenterPoint.x - lastCenterPoint.x);//x滑动的距离
                        int focalX = scrollX; //焦点X坐标

                        int endX = currentCenterPoint.x * 2; //未查询区域消的结束点X坐标
                        int scrollY = Math.abs(currentCenterPoint.y - lastCenterPoint.y);//Y方向滑动距离

                        int endY = currentCenterPoint.y * 2;//未查询取消结束点Y坐标
                        if (currentCenterPoint.y - lastCenterPoint.y > 0) {
                            Log.d(TAG, "onCameraChangeFinish: 地图 向左边、 向下滑动");
                            int focalY = endY - scrollY;// 焦点Y坐标
                            //从焦点开始，顺时针转动，确定6个点
                            Point point1 = new Point(focalX, focalY);//交点
                            Point point2 = new Point(endX, focalY);
                            Point point3 = new Point(endX, endY);
                            Point point4 = new Point(0, endY);
                            Point point5 = new Point(0, 0);
                            Point point6 = new Point(focalX, 0);

                            genPointList(pointList, point1, point2, point3, point4, point5, point6);
                        } else {
                            Log.d(TAG, "onCameraChangeFinish: 地图向左边 向上滑动");
                            int focalY = scrollY;
                            //从焦点开始，顺时针转动，确定6个点
                            Point point1 = new Point(focalX, focalY);//交点
                            Point point2 = new Point(focalX, endY);
                            Point point3 = new Point(0, endY);
                            Point point4 = new Point(0, 0);
                            Point point5 = new Point(endX, 0);
                            Point point6 = new Point(endX, focalY);
                            genPointList(pointList, point1, point2, point3, point4, point5, point6);

                        }
                    }

                    //做多边形搜索

                    polygonNearbySearch(pointList);


                } else {//和上次滑动没有区域重叠，只需要获取 左上和右下两个位置的经纬度即可
                    Log.d(TAG, "onCameraChangeFinish: 和上次滑动没有区域重叠");
                    nearbySearch(currentCenterPoint);
                }


                lastCameraCenter = target;
                lastZoom = zoom;

            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getObject() instanceof Topic) {

                    //判断是否有被点击过的 marker ，如果有，需要设置回 主题对应的图标
                    if (lastSelectPosition != null && lastSelectPosition <= topicMarkerList.size() - 1) {
                        Marker lastSelectMarker = topicMarkerList.get(lastSelectPosition);
                        lastSelectMarker.setIcon(getBitmapDescriptor(((Topic) lastSelectMarker.getObject()).getType()));
                    }
                    lastSelectPosition = topicMarkerList.indexOf(marker);
//                    TopicDialog bottomTopicList = new TopicDialog(getActivity(), resultsList); //对话框的方式，当对话框弹出后，地图没法操作了
//                    bottomTopicList.show();

                    if (bottomTopicListV1 != null) {
                        bottomTopicListV1.show(lastSelectPosition);
                    } else {
                        Log.e(TAG, "onMarkerClick: bottomTopicList未空，，，，");
                    }
                    marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_icon));//显示默认 小定位蓝点
                    marker.showInfoWindow();
                    moveCamera(marker.getPosition(), zoom);
                } else if (marker.getObject() instanceof User) {
                    marker.showInfoWindow();
                    moveCamera(marker.getPosition(), zoom);
                }
                return true;//返回true 地图不会移动到 maker 的中心点，，默认返回 false
            }
        });
        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                if (marker.getObject() instanceof Topic) {
                    //  pushTopic = (Topic) marker.getObject();
                    return generateTopicLocationView((Topic) marker.getObject());
                } else if (marker.getObject() instanceof User) {

                    User targetUser = (User) marker.getObject();

                    return generateUserLocationView(targetUser);

                }
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });


//        mBaiduMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
//            @Override
//            public void onCameraChange(CameraPosition cameraPosition) {
//
//            }
//
//            @Override
//            public void onCameraChangeFinish(CameraPosition cameraPosition) {
//
//                LatLng latLng = cameraPosition.target;
//                //地图移动了，改变罗盘模式为普通模式
//                android.graphics.Point slidePoint = mBaiduMap.getProjection().toScreenLocation(latLng);
//                android.graphics.Point llPoint = mBaiduMap.getProjection().toScreenLocation(locationLatLon);
//                if (slidePoint == null || llPoint == null) {
//                    return;
//                }
//                if ((Math.abs(slidePoint.x - llPoint.x) > screenWidth / 12 || Math.abs(slidePoint.y - llPoint.y) > screenHeight / 12))//
//                {
//                    if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_MAP_ROTATE) {
//                        btnMapStatus.setBackgroundResource(R.drawable.tx_map_location);
//                        mBaiduMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只定位一次，地图和图标都不旋转
//
//                    }
//
//                    //setLocationIcon(null);
//                }
//
//            }
//        });

        //markerClickListener();
    }

    /**
     * marker 隐藏掉落动画
     *
     * @param marker
     */
    private void markerHideAnimation(Marker marker) {
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        }
        Point point = aMap.getProjection().toScreenLocation(marker.getPosition());
        point.y += Utils.dpToPx(200, getActivity());
        TranslateAnimation translateAnimation = new TranslateAnimation(aMap.getProjection().fromScreenLocation(point));
        translateAnimation.setDuration(1000);
        translateAnimation.setInterpolator(new AccelerateInterpolator());
        ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 0, 1f, 0);
        scaleAnimation.setDuration(1000);
        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(translateAnimation);
        animationSet.addAnimation(scaleAnimation);
        animationSet.setAnimationListener(new com.amap.api.maps.model.animation.Animation.AnimationListener() {
            @Override
            public void onAnimationStart() {

            }

            @Override
            public void onAnimationEnd() {
                marker.destroy();
                if (topicMarkerList.size() == 0 && userMarkerList.size() == 0) {
                    markerAnimoteOuting = false;
                }
            }
        });
        marker.setAnimation(animationSet);
        marker.startAnimation();
    }

    private void nearbySearch(Point currentCenterPoint) {
        LatLng topLeft = aMap.getProjection().fromScreenLocation(new Point(0, 0));
        LatLng bottomRight = aMap.getProjection().fromScreenLocation(new Point(currentCenterPoint.x * 2, currentCenterPoint.y * 2));
        //判断两个顶点经纬度的位置，是否需要交换
        if (topLeft.latitude < bottomRight.latitude) {
            LatLng temp = topLeft;
            topLeft = bottomRight;
            bottomRight = temp;
        }
        boundingBoxNearbySearch(topLeft, bottomRight);
    }

    private void genPointList(List<com.srwl.mytx.domain.LatLng> pointList, Point point1, Point point2, Point point3, Point point4, Point point5, Point point6) {
        LatLng latLng1 = aMap.getProjection().fromScreenLocation(point1);
        LatLng latLng2 = aMap.getProjection().fromScreenLocation(point2);
        LatLng latLng3 = aMap.getProjection().fromScreenLocation(point3);
        LatLng latLng4 = aMap.getProjection().fromScreenLocation(point4);
        LatLng latLng5 = aMap.getProjection().fromScreenLocation(point5);
        LatLng latLng6 = aMap.getProjection().fromScreenLocation(point6);

        pointList.add(new com.srwl.mytx.domain.LatLng(latLng1.latitude, latLng1.longitude));
        pointList.add(new com.srwl.mytx.domain.LatLng(latLng2.latitude, latLng2.longitude));
        pointList.add(new com.srwl.mytx.domain.LatLng(latLng3.latitude, latLng3.longitude));
        pointList.add(new com.srwl.mytx.domain.LatLng(latLng4.latitude, latLng4.longitude));
        pointList.add(new com.srwl.mytx.domain.LatLng(latLng5.latitude, latLng5.longitude));
        pointList.add(new com.srwl.mytx.domain.LatLng(latLng6.latitude, latLng6.longitude));
    }

    private int getSearchRadius() {
        //当前地图级别下1像素点对应的距离长度（米）
        float scalePerPixel = aMap.getScalePerPixel();
        //搜索半径（公里）
        int searchRadius = (int) (scalePerPixel * screenWidth / 2) / 1000;
        if (searchRadius < 1) {
            searchRadius = 1;
        }
        return searchRadius;
    }

    /**
     * 当拖动地图或者缩放地图的时候，搜索当前范围内的主题
     */
    private void boundingBoxNearbySearch(LatLng topLeft, LatLng bottomRight) {

        if (isNearbySearching) {
            return;
        }
        //  aMap.clear(true);
        isNearbySearching = true;
        Map<String, Object> body = new HashMap<>();
        body.put("tl_lat", topLeft.latitude);
        body.put("tl_lon", topLeft.longitude);
        body.put("br_lat", bottomRight.latitude);
        body.put("br_lon", bottomRight.longitude);

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .boundingBoxNearbySearch(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        isNearbySearching = false;
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES附近查询失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES附近查询失败：" + result.getMsg());
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) result.getData();
                        //清空保存的marker集合
                        // topicMarkerList.clear();
                        //   resultsList.clear();
                        List<Topic> hits = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        for (Topic topic : resultsList) {
                            for (int i = 0; i < hits.size(); i++) {
                                if (TextUtils.equals(topic.getId(), hits.get(i).getId())) {
                                    hits.remove(i);
                                    i--;
                                }
                            }
                        }
                        resultsList.addAll(hits);
                        if (bottomTopicListV1 != null && bottomTopicListV1.isShown()) {
                            bottomTopicListV1.notifyDataSetChange();
                        }
                        showMultiMarker(hits, false);
                        Log.d(TAG, "ES附近查询完成 搜索到" + resultsList.size() + "条数据，  " + jsonObject);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        isNearbySearching = false;
                    }
                });
    }

    private void polygonNearbySearch(List<com.srwl.mytx.domain.LatLng> pointList) {
        //清空保存的marker集合
        //topicMarkerList.clear();
        //  handler.removeCallbacks(autoShowInfoWindow);
        if (isNearbySearching) {
            return;
        }
        //aMap.clear(true);
        isNearbySearching = true;

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .polygonNearbySearch(pointList)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        isNearbySearching = false;
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "多边形附近搜索失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "多边形附近搜索失败：" + result.getMsg());
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) result.getData();
                        // resultsList.clear();
                        List<Topic> hits = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        if (hits.size() == 0) {
                            Log.d(TAG, "多边形附近搜索，没搜到内容");
                            return;
                        }
                        for (Topic topic : resultsList) {
                            for (int i = 0; i < hits.size(); i++) {
                                if (TextUtils.equals(topic.getId(), hits.get(i).getId())) {
                                    hits.remove(i);
                                    i--;
                                }
                            }
                        }
                        resultsList.addAll(hits);
                        if (bottomTopicListV1 != null && bottomTopicListV1.isShown()) {
                            bottomTopicListV1.notifyDataSetChange();
                        }
                        showMultiMarker(hits, false);
                        Log.d(TAG, "多边形附近搜索完成 搜索到" + hits.size() + "条" + jsonObject);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        isNearbySearching = false;
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_map_status:
                if (!followMove) {
                    location();
                    followMove = true;
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(19));
                    btnMapStatus.setBackgroundResource(R.drawable.showbtn);
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));

                } else if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_LOCATE) {
                    btnMapStatus.setBackgroundResource(R.drawable.tx_map_navigation_big);
                    //设置地图倾斜度
                    aMap.animateCamera(CameraUpdateFactory.changeBearing(45));
                    aMap.animateCamera(CameraUpdateFactory.changeTilt(50));


                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass2));
                    aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER));//连续定位图标旋转，不自动回到定位中心点

                } else if (myLocationStyle.getMyLocationType() == MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER) {
                    btnMapStatus.setBackgroundResource(R.drawable.showbtn);
                    aMap.animateCamera(CameraUpdateFactory.changeBearing(0));
                    aMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass3));
                    aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只定位一次，定位时自动回到中心点，地图和图标都不旋转

                } else {
                    btnMapStatus.setBackgroundResource(R.drawable.compass);
                    aMap.animateCamera(CameraUpdateFactory.changeTilt(50));
                    //  mBaiduMap.animateCamera(CameraUpdateFactory.changeBearing(90));
                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass1));
                    aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER));//连续定位，地图旋转,不自动回到定位中心点
                }

                break;
            case R.id.btn_publish:
//                if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
//                    getContext().startActivity(new Intent(getContext(), LoginActivity.class).putExtra("EXTRA_CONTENT", "发布信息需要先登录"));
//                    return;
//                }
//                String phoneNumber = UserProfileManager.getInstance().getUserPhoneNumber();
//                if (TextUtils.isEmpty(phoneNumber)) {
//                    ConfirmDialog confirmDialog = new ConfirmDialog(getContext(), "提示", "绑定手机号才可以发布主题，去绑定？", true);
//                    confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                        @Override
//                        public void confirm() {
//                            startActivity(new Intent(getActivity(), UpdateUserInfoActivity.class));
//                        }
//                    });
//                    confirmDialog.show();
//                } else {
//                    startActivity(new Intent(getActivity(), PublishTopicActivity.class));
//                }
                startActivity(new Intent(getActivity(), PublishTopicActivity.class));
                break;
            case R.id.btn_3d_switch:
                if (aMap.getMapType() == AMap.MAP_TYPE_SATELLITE) {
                    btn_3dSwitch.setBackgroundResource(R.drawable.mapswitch04);
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);
                } else {
                    btn_3dSwitch.setBackgroundResource(R.drawable.mapswitch05);
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                }
                break;
            case R.id.btn_show_contact:

                if (!mDrawerLayout.isDrawerOpen(contactListView)) {
                    mDrawerLayout.openDrawer(contactListView);
                }
                break;

            case R.id.iv_topic_list:
//                if (listener != null) {
//                    listener.onChangeFragment();
//                }
                startActivity(new Intent(getActivity(), TopicListActivity.class));
                break;
            case R.id.iv_scale_add:
                bol_needNearbySearch = true;
                aMap.animateCamera(CameraUpdateFactory.zoomIn());
                break;

            case R.id.iv_scale_reduce:
                bol_needNearbySearch = true;
                aMap.animateCamera(CameraUpdateFactory.zoomOut());
                break;
            case R.id.iv_search:
                startActivity(new Intent(getContext(), TopicSearchActivity.class));
//            case R.id.btn_search:
//                searchView.setVisibility(View.VISIBLE);
//                searchView.setBackground(new ColorDrawable(Color.WHITE));
//                showSearchHistory();
//                rv_search.setVisibility(View.VISIBLE);
//                break;
            /*case R.id.btn_track_query:

                //定位
                location();
                btnMapStatus.setVisibility(View.VISIBLE);
                btn_trackQuery.setVisibility(View.INVISIBLE);


                break;*/
        }
    }


    private void location(LatLng latLng) {

        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 16, 30, 30)));//经纬度，缩放级别，倾斜度，角度（可视区域指向的方向）
    }

    //定位
    public void location() {
//        aMap.animateCamera(CameraUpdateFactory.changeBearing(0));
//        aMap.animateCamera(CameraUpdateFactory.changeTilt(50));
        if (firstLocationSuccess) {//已经定位成功了，再次定位，就移动到定位点，
            aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));//只定位一次，定位时自动回到中心点，地图和图标都不旋转
        } else {//还没定位成功，只获取经纬度，而不移动地图，否则会出现 获取热点数据后，marker刚显示处理，地图一下子又移动到 定位点了。
            aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW));//定位一次，不移动地图
        }

        // locationClient.locationOnce();
    }

    public void setBottomTopicList(BottomTopicListV1 bottomTopicListV1) {
        this.bottomTopicListV1 = bottomTopicListV1;
        bottomTopicListV1.init(resultsList);
        bottomTopicListV1.bottomTopicAdapter.setCallbackToOutside(new BottomTopicListAdapter.CallbackToOutside() {
            @Override
            public void jumpPage(Topic topic) {
                //跳转页面
                startActivityForResult(new Intent(getContext(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), REQUEST_CODE_TO_TOPIC_DETAIL);
            }

            @Override
            public void commentJumpPage(Topic topic) {
                //点击评论图标的回调,跳转到主题详情页面，跳转时携带标示评论的数据
                startActivityForResult(new Intent(getContext(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic)
                        .putExtra(Constant.EXTRA_INFO_MESSAGE, "comment"), REQUEST_CODE_TO_TOPIC_DETAIL);
            }
        });

        bottomTopicListV1.setListener(new BottomTopicListV1.InteractionListener() {
            @Override
            public void onPageChange(int position) {

                if (lastSelectPosition == null) {
                    lastSelectPosition = position;
                    return;
                }
                if (position > topicMarkerList.size() - 1 || position == lastSelectPosition) {
                    return;
                }
                if (lastSelectPosition <= topicMarkerList.size() - 1) {
                    Marker lastSelectMarker = topicMarkerList.get(lastSelectPosition);
                    Object object = lastSelectMarker.getObject();
                    if (object != null && object instanceof Topic) {
                        lastSelectMarker.setIcon(getBitmapDescriptor(((Topic) object).getType()));
                    }
                }
                lastSelectPosition = position;

                Marker marker = topicMarkerList.get(position);
                marker.showInfoWindow();
                marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_icon));//显示默认 小定位蓝点
                moveCamera(marker.getPosition(), zoom);
            }

            @Override
            public void onScrolled(float dy) {
                //因为mainActivity的bottomBar 高度是55dp ,所以移动的高度应该先减去这个高度，
                float scrollY = dy - 55 * density;
                if (scrollY >= 0) {
                    clZoomContainer.setTranslationY(-scrollY);
                    btnMapStatus.setTranslationY(-scrollY);
                } else {
                    clZoomContainer.setTranslationY(0);
                    btnMapStatus.setTranslationY(0);
                }
            }

            @Override
            public void onHide() {
                if (lastSelectPosition == null || lastSelectPosition > topicMarkerList.size() - 1) {
                    return;
                }
                Marker lastSelectMarker = topicMarkerList.get(lastSelectPosition);
                lastSelectMarker.hideInfoWindow();
                lastSelectMarker.setIcon(getBitmapDescriptor(((Topic) lastSelectMarker.getObject()).getType()));
            }
        });
    }

    @Override
    public void onMyLocationChange(Location location) {
        //这个回调并不一定是定位成功
        if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0) {
            Log.d(TAG, "定位成功：  getLatitude：" + location.getLatitude() + "  getLongitude():" + location.getLongitude());

            com.srwl.mytx.domain.LatLng locationLatLon = new com.srwl.mytx.domain.LatLng(location.getLatitude(), location.getLongitude());
            // mapView.postDelayed(() -> location(locationLatLon), 300);
            //   location(locationLatLon);
            if (!firstLocationSuccess) {
                firstLocationSuccess = true;
                if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                    autoSearchWithTempUser(locationLatLon);
                } else {
                    autoSearch(locationLatLon);
                }
            }
        } else {
            tryLocationCount++;
            Log.d(TAG, "onMyLocationChange: 定位失败,重启定位,tryLocationCount:" + tryLocationCount);
            if (tryLocationCount < 5) {
                handler.postDelayed(
                        new Runnable() {
                            @Override
                            public void run() {
                                location();
                            }
                        }
                        , tryLocationCount * 1000);
            }
        }
    }


    private void autoSearch(com.srwl.mytx.domain.LatLng latLng) {

        Map<String, Object> body = new HashMap<>();
        body.put("page", 1);
        body.put("size", 5);
        body.put("location", latLng);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .autoSearch(body).
                enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES自动搜索失败：" + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "ES自动搜索失败：" + result.getMsg());
                            return;
                        }
                        JSONArray jsonArray = (JSONArray) result.getData();
                        if (jsonArray == null) return;
                        List<Topic> topics = jsonArray.toJavaList(Topic.class);
                        for (Topic topic : resultsList) {
                            for (int i = 0; i < topics.size(); i++) {
                                if (TextUtils.equals(topic.getId(), topics.get(i).getId())) {
                                    topics.remove(i);
                                    i--;
                                }
                            }
                        }
                        resultsList.addAll(topics);
                        Log.d(TAG, "onResponse: 加载 最热数据 完成" + jsonArray);
                        showMultiMarker(topics, true);
                        // location(latLng);
                        //showMultiPoint(resultsList);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void autoSearchWithTempUser(com.srwl.mytx.domain.LatLng latLng) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", 1);
        body.put("size", 5);
        body.put("location", latLng);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .queryHottestTopic(body).
                enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES自动搜索失败：" + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "ES自动搜索失败：" + result.getMsg());
                            return;
                        }
                        if (result.getData() == null) {
                            return;
                        }
                        JSONArray jsonArray = (JSONArray) result.getData();

                        List<Topic> topics = jsonArray.toJavaList(Topic.class);
                        resultsList.clear();
                        resultsList.addAll(topics);
                        Log.d(TAG, "onResponse: 加载 最热数据 完成" + jsonArray);
                        showMultiMarker(resultsList, true);
                        // location(latLng);
                        //showMultiPoint(resultsList);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void showSingleMarker(Topic topic) {

        if (topic == null) {
            return;
        }
        for (Topic searchTopic : resultsList) { //推送的主题和搜索的主题去重
            if (TextUtils.equals(topic.getId(), searchTopic.getId())) {
                Log.w(TAG, "showSingleMarker: 推送的主题和搜索结果中的主题信息重复了，，" + topic.toString());
                return;
            }
        }


        LatLng latLng = new LatLng(topic.getLocation().getLatitude(), topic.getLocation().getLongitude());
        MarkerOptions markerOption = new MarkerOptions()
                .position(latLng)
                .title(topic.getTitle())
                .snippet(topic.getContent())
                .draggable(true);

        Marker marker = aMap.addMarker(markerOption);
        marker.setObject(topic);
        marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_icon));//显示默认 小定位蓝点
        marker.showInfoWindow();
        moveCamera(latLng, 18);
        //把推送生成的marker 也放进topicMarkerList 集合中，否则晃动地图，无法清除
        topicMarkerList.add(marker);
        resultsList.add(topic);
        bottomTopicListV1.notifyDataSetChange();
    }

    /**
     * @param resultsList
     * @param zoom        是否缩放地图 ，在一个屏幕之内显示全部 marker
     */
    private void showMultiMarker(List<Topic> resultsList, boolean zoom) {
        if (resultsList.size() == 0) {
            return;
        }
        //aMap.clear(true);//参数 true 表示只清除覆盖物

        List<LatLng> pointList = new ArrayList<>();
        for (int i = 0, resultsListSize = resultsList.size(); i < resultsListSize; i++) {
            Topic topic = resultsList.get(i);

            LatLng latLng = new LatLng(topic.getLocation().getLatitude(), topic.getLocation().getLongitude());
            pointList.add(latLng);
            MarkerOptions markerOption = new MarkerOptions()
                    .position(latLng)
                    .title(topic.getTitle())
                    .snippet(topic.getContent())
                    .draggable(true)
                    .snippet(topic.getTitle());

            markerOption.icon(getBitmapDescriptor(topic.getType()));


            final Marker maker = aMap.addMarker(markerOption);
            maker.setObject(topic);

            topicMarkerList.add(maker);
        }

        //开始自动 显示 infoWindow
//        if (topicMarkerList.size() != 0 && !hidden) {
//            handler.post(autoShowInfoWindow);
//        }

        //附近搜索的时候，不缩放屏幕去适配marker 的显示
        if (zoom) {
            zoomToSpanWithCenter(pointList);
        }

    }

    private BitmapDescriptor getBitmapDescriptor(Integer type) {
        BitmapDescriptor bitmapDescriptor;
        switch (type) {
            case Constant.TOPIC_TYPE_SCHOOL:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_school);
                break;
            case Constant.TOPIC_TYPE_EXPOSE:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_expose);
                break;
            case Constant.TOPIC_TYPE_REWARD:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_reward);
                break;
            case Constant.TOPIC_TYPE_AREA:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_area_1);
                break;
            case Constant.TOPIC_TYPE_INDUSTRY:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.tx_marker_industry);
                break;
            default:
                bitmapDescriptor = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);
        }
        return bitmapDescriptor;
    }

    /**
     * 展示海量点
     *
     * @param resultsList
     */
    private void showMultiPoint(List<Topic> resultsList) {
        MultiPointOverlayOptions overlayOptions = new MultiPointOverlayOptions();
        overlayOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));//设置图标
        overlayOptions.anchor(0.5f, 0.5f); //设置锚点
        MultiPointOverlay multiPointOverlay = aMap.addMultiPointOverlay(overlayOptions);

        List<MultiPointItem> list = new ArrayList<MultiPointItem>();

        for (Topic topic : resultsList) {
            LatLng latLng = new LatLng(topic.getLocation().getLatitude(), topic.getLocation().getLongitude());
            MultiPointItem multiPointItem = new MultiPointItem(latLng);
            multiPointItem.setObject(topic);
            list.add(multiPointItem);

        }

        multiPointOverlay.setItems(list);
    }


    public void zoomToSpanWithCenter(List<LatLng> pointList) {
        if (pointList != null && pointList.size() > 0) {
            if (aMap == null)
                return;

            LatLngBounds bounds = getLatLngBounds(pointList.get(0), pointList);
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
        }
    }

    private void moveCamera(LatLng latLng, float zoom) {

        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                latLng, zoom, 30, 30));
        aMap.animateCamera(cameraUpdate);
    }

    //根据中心点和自定义内容获取缩放bounds
    private LatLngBounds getLatLngBounds(LatLng centerpoint, List<LatLng> pointList) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (centerpoint != null) {
            for (int i = 0; i < pointList.size(); i++) {
                LatLng p = pointList.get(i);
                LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
                b.include(p);
                b.include(p1);
            }
        }
        return b.build();
    }

//    @Override
//    public void onLocationChanged(AMapLocation aMapLocation) {
//
//        //mapview 销毁后不做操作
//        if (aMapLocation == null && mBaiduMap == null)
//            return;
//        // 构造定位数据
//        int mCurrentDirection = 0;
//
//        double mCurrentLat = aMapLocation.getLatitude();
//        double mCurrentLong = aMapLocation.getLongitude();
//        ll = new LatLng(mCurrentLat, mCurrentLong);
//        if (slidell == null) {
//            slidell = ll;
//        }
//
//        // Log.w("经纬度", mCurrentLat+"--"+mCurrentLong);
//        //  pt = new LatLng(mCurrentLat, mCurrentLong);
//        // 设置定位数据
//        //  if (location.get)
//
//      location(new LatLng(mCurrentLat,mCurrentLong));
//        //创建定位光标
//
//        if (isFirstLocation) {
//            isFirstLocation = false;
//            location(ll);
//            //  mLocationClient.stop();
//            if (mCurrentLat != mCurrentLatOld && mCurrentLat != 0.0) {
//                mCurrentLatOld = mCurrentLat;
//
//
//            }
//        }
//    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden) {
            isContinue = true;
            handler.post(showPushTopic);

        } else {//当隐藏的时候，如果显示推送topic的循环还在继续，中断
            handler.removeCallbacks(showPushTopic);
            isContinue = false;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
//aMapView.onResume();
        mapView.onResume();
        //  refreshMessageList();
        // updateNoticeUnreadText();
    }

    @Override
    public void onPause() {
        super.onPause();
        // aMapView.onPause();
        mapView.onPause();
//        if (!mLocationClient.isStarted()) {
//            mLocationClient.stopLocation();
//        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // aMapView.onDestroy();
        mapView.onDestroy();
        // mLocationClient.onDestroy();
        PermissionsUtils.getInstance().clear();
        broadcastManager.unregisterReceiver(broadcastReceiver);
        JzvdStd.resetAllVideos();

    }

    public String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    public void refresh() {
        // getContactList();
        // updateNoticeUnreadText();
        if (contactListView != null) {
            contactListView.refresh(Helper.getInstance().getContactList());
        }
        //adapter.notifyDataSetChanged();
    }

    public void onContactGroupModelChange() {
        contactListView.onContactGroupModelChange();
    }


    public void createUserLocationMaker(final Intent intent) {
        final User targetUser = intent.getExtras().getParcelable(EaseConstant.EXTRA_TARGET_USER);
        if (targetUser == null) {
            return;
        }
        com.srwl.mytx.domain.LatLng latLng1 = targetUser.getLatLng();
        if (latLng1.getLatitude() == 0.0 || latLng1.getLongitude() == 0.0) {
            return;
        }
        final LatLng latLng = new LatLng(targetUser.getLatLng().getLatitude(), targetUser.getLatLng().getLongitude());
//        GlideApp.with(context).load(targetUser.getAvatar()).override((int) (MAKER_HEIGHT * dm.density), (int) (MAKER_HEIGHT * dm.density))
//
//                .error(R.drawable.tx_default_avatar)
//                .into(simpleTarget1);
        if (GlideLoadUtils.isActivityAlive(getActivity())) {

            RequestOptions options = new RequestOptions()
                    .error(R.drawable.tx_default_avatar_1)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .override((int) (MAKER_HEIGHT * density), (int) (MAKER_HEIGHT * density));

            Glide.with(getActivity()).asBitmap().load(targetUser.getAvatar()).apply(options).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                    MarkerOptions markerOptions = new MarkerOptions()
                            .position(latLng)
                            // .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                            .icon(BitmapDescriptorFactory.fromBitmap(resource))
                            .zIndex(0)
                            .draggable(false);

                    Marker mMarker = aMap.addMarker(markerOptions);
                    mDrawerLayout.closeDrawer(contactListView);

                    mMarker.setObject(intent.getParcelableExtra(EaseConstant.EXTRA_TARGET_USER));
                    mMarker.showInfoWindow();
                    mMarker.setDraggable(true);
                    userMarkerList.add(mMarker);
                    location(latLng);
                }
            });
        }
    }


    @NonNull
    private View generateUserLocationView(User targetUser) {
        View viewInfoWindow = LayoutInflater.from(getActivity()).inflate(R.layout.baidu_maker_infowindow, null);
        TextView tv_name = viewInfoWindow.findViewById(R.id.tv_name);
        TextView tv_address = viewInfoWindow.findViewById(R.id.tv_address);
        TextView tv_time = viewInfoWindow.findViewById(R.id.tv_time);
        // View btn_chat = viewInfoWindow.findViewById(R.id.btn_chat);
        ImageView iv_avatar = viewInfoWindow.findViewById(R.id.iv_avatar);
        ImageView iv_navigation = viewInfoWindow.findViewById(R.id.btn_navigation);
        //Glide.with(this).load(targetUser.getAvatar()).error(R.drawable.tx_default_avatar).into(iv_avatar);
        GlideLoadUtils.glideLoad(getActivity(), targetUser.getAvatar(), iv_avatar, R.drawable.tx_default_avatar_1);
        tv_name.setText(targetUser.getUsername());
        tv_address.setText(targetUser.getArea());
        tv_time.setText(DateUtils.getTimestampString(targetUser.getCreated()));
        viewInfoWindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
            }
        });
        iv_navigation.setOnClickListener(v -> showSelectNaviDialog(targetUser.getLatLng().getLongitude(), targetUser.getLatLng().getLatitude(), targetUser.getArea()));
        return viewInfoWindow;
    }

    @NonNull
    private View generateTopicLocationView(Topic topic) {

        View view = LayoutInflater.from(getContext()).inflate(R.layout.topic_infowindow_layout_v2, null);
        // TextView tv_title = view.findViewById(R.id.tv_title);
        //TextView tv_content = view.findViewById(R.id.tv_content);
        ImageView iv_topicType = view.findViewById(R.id.iv_topic_type);
        // tv_title.setText(pushTopic.getTitle());
        // tv_content.setText(topic.getContent());

        if (topic.getType() != null) {

            switch (topic.getType()) {

                case Constant.TOPIC_TYPE_REWARD:
                    iv_topicType.setImageResource(R.drawable.tx_infowindow_reward);
                    break;
                case Constant.TOPIC_TYPE_EXPOSE:
                    //    tv_title.setTextColor(getResources().getColor(R.color.topic_type_expose_red));
                    iv_topicType.setImageResource(R.drawable.tx_infowindow_expose);
                    break;
                case Constant.TOPIC_TYPE_AREA:
                    iv_topicType.setImageResource(R.drawable.tx_infowindow_area);
                    break;
                case Constant.TOPIC_TYPE_INDUSTRY:
                    iv_topicType.setImageResource(R.drawable.tx_infowindow_industry);
                    break;
                case Constant.TOPIC_TYPE_SCHOOL:
                    iv_topicType.setImageResource(R.drawable.tx_infowindow_school_1);

                    break;
                case Constant.TOPIC_TYPE_FOUND:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_found);
                    break;
                case Constant.TOPIC_TYPE_GIFT:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_gift);
                    break;
                case Constant.TOPIC_TYPE_AUCTION:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_auction);
                    break;
                case Constant.TOPIC_TYPE_GOODS:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_goods);
                    break;
                case Constant.TOPIC_TYPE_SHOW:
                    iv_topicType.setImageResource(R.drawable.tx_topic_type_show);
                    break;


                default:
                    iv_topicType.setVisibility(View.GONE);

            }
        }
        // InfoWindowView infoWindowView = new InfoWindowView(getContext(), searchResultList.get(position));
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), REQUEST_CODE_TO_TOPIC_DETAIL_FROM_PUSH_MESSAGE);
            }
        });
        return view;
    }

    private void showProgressBar(boolean isShowProgressBar) {
        if (isShowProgressBar && !progressBar.isShown()) {
            progressBar.setVisibility(View.VISIBLE);
        } else if (!isShowProgressBar && progressBar.isShown()) {
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {


        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
        double latitude = amapLocation.getLatitude();//获取纬度
        double longitude = amapLocation.getLongitude();//获取经度
        amapLocation.getAccuracy();//获取精度信息

        Log.d(TAG, "onLocationChanged: latitude" + latitude + " latitude" + longitude);
        location(new LatLng(latitude, longitude));
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        aMap.setMyLocationStyle(myLocationStyle);

    }

    /**
     * 收到推送的主题
     *
     * @param intent
     */
    public void receivePushTopic(Intent intent) {
        Topic topic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        Date date = topic.getUpdated() != null ? topic.getUpdated() : topic.getCreated();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -2);
        Date twoDaysAgo = calendar.getTime();

        //如果主题的创建或者更新时间在2天以前就丢弃
        if (twoDaysAgo.after(date)) {
            return;
        }

        pushTopicList.add(topic);
        if (pushTopicList.size() > 30) { //超过30条，就清理掉最前面的
            pushTopicList.remove(0);
        }


        //当当前fragment没有隐藏，且循环已经中断的情况下，调用handler 立即显示当前收到的推送topic
        if (!hidden && !isContinue) {
            handler.post(showPushTopic);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "onRequestPermissionsResult: 收到权限请求回调");
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {
        tryLocationCount = 0;
        location();
    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {

    }


    /**
     * 当点击返回的时候，如果搜索栏 属于展开状态，那么折叠搜索栏，并消费掉这次返回点击
     *
     * @return
     */
    public boolean onBackClick() {
//        if (!searchView.isIconified() && rv_search.isShown()) {
//            searchView.onActionViewCollapsed();
//            closeSearchView();
//            return true;
//        }
        return false;
    }


    public List<String> getApkList(Context context) { //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        return packageNames;
    }

    private List<String> getMapApk() {
        List<String> itemList = new ArrayList<>();
        List<String> apkList = getApkList(getActivity());
        if (apkList.contains("com.autonavi.minimap")) {

            itemList.add("高德地图");
        }
        if (apkList.contains("com.baidu.BaiduMap")) {
            itemList.add("百度地图");
        }
        if (apkList.contains("com.tencent.map")) {

            itemList.add("腾讯地图");
        }

        return itemList;
    }

    private void showSelectNaviDialog(double longitude, double latitude, String address) {

        List<String> mapApk = getMapApk();
        if (mapApk.size() == 0) {
            showToast("在您手机上暂未找到导航软件...");
            return;
        }
        BottomDialog bottomDialog = new BottomDialog(getActivity(), mapApk, new BottomDialog.InteractionListener() {
            @Override
            public void onDialogItemViewClick(int position, String itemName) {
                Intent intent;
                switch (itemName) {
                    case "高德地图":

//
//                        intent = new Intent("androidamap://route?sourceApplication=" + getResources().getString(R.string.app_name) + "&sname=我的位置&dlat="
//                                + latitude + "&dlon=" + longitude + "&dname=" + "标题" + "&dev=1&m=2&t=3");
//                        startActivity(intent);
                        String uriString = null;
                        StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=" + getResources().getString(R.string.app_name));
                        builder.append("&dlat=").append(latitude)
                                .append("&dlon=").append(longitude)
                                .append("&dname=").append(address)
                                .append("&dev=0")
                                .append("&t=0");
                        uriString = builder.toString();
                        intent = new Intent(Intent.ACTION_VIEW);
                        intent.setPackage("com.autonavi.minimap");
                        intent.setData(Uri.parse(uriString));
                        startActivity(intent);

                        break;

                    case "百度地图":
                        intent = new Intent();
                        // double[] doubles = gaoDeToBaidu(latitude, longitude);
                        intent.setData(Uri.parse("baidumap://map/direction?coord_type=gcj02&destination=" + latitude + "," + longitude + "&mode=driving"));
                        startActivity(intent);

                        break;

                    case "腾讯地图":
//                        intent = new Intent();
//                        intent.setAction(Intent.ACTION_VIEW);
//                        intent.addCategory(Intent.CATEGORY_DEFAULT);
//                        //将功能Scheme以URI的方式传入data
//                        Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=" + address + "&tocoord=" + latitude + "," + longitude);
//                        intent.setData(uri);
//                        startActivity(intent);

                        String uriString1 = null;
                        StringBuilder builder1 = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=zhongshuo");

                        builder1.append("&to=").append(address)
                                .append("&tocoord=").append(latitude)
                                .append(",")
                                .append(longitude);
                        uriString = builder1.toString();
                        intent = new Intent(Intent.ACTION_VIEW);
                        intent.setPackage("com.tencent.map");
                        intent.setData(Uri.parse(uriString));
                        startActivity(intent);

                        break;

                }
            }
        });
        bottomDialog.show();

    }

    public void setListener(MainActivity.ChangeFragmentListener listener) {
        this.listener = listener;
    }

    /**
     * @author Administrator
     * @time 2018/5/14  13:35
     * @describe 高德转百度（火星坐标gcj02ll–>百度坐标bd09ll）
     */
    @Deprecated
    public double[] gaoDeToBaidu(double gd_lat, double gd_lon) {
        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double tempLon = z * Math.cos(theta) + 0.0065;
        double tempLat = z * Math.sin(theta) + 0.006;
        double[] gps = {tempLat, tempLon};
        return gps;
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_TOPIC_EDIT_CHANGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    //主题编辑改变监听
                    case Constant.ACTION_TOPIC_EDIT_CHANGED:
                        Topic updateTopic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                        for (int i = 0; i < resultsList.size(); i++) {
                            Topic topic = resultsList.get(i);
                            if (topic.getId().equals(updateTopic.getId())) {
                                resultsList.remove(i);
                                resultsList.add(i, updateTopic);
                                if (bottomTopicListV1 != null) {
                                    bottomTopicListV1.notifyItemChange(i);
                                }
                                break;
                            }
                        }
                        break;

                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK || data == null) {
            return;
        }
//        if (requestCode == REQUEST_CODE_TO_TOPIC_DETAIL) {
//            Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
//
//            for (int i = 0; i < searchResultList.size(); i++) {
//                Topic topic = searchResultList.get(i);
//                if (topic.getId().equals(updateTopic.getId())) {
//                    searchResultList.remove(i);
//                    searchResultList.add(i, updateTopic);
//                    searchResultAdapter.notifyItemChanged(i);
//                    break;
//                }
//            }
//        } else
        if (requestCode == REQUEST_CODE_TO_TOPIC_DETAIL) {
            Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
            if (updateTopic == null) {
                return;
            }
            for (int i = 0; i < resultsList.size(); i++) {
                Topic topic = resultsList.get(i);
                if (TextUtils.equals(updateTopic.getId(), topic.getId())) {
                    //主题被删除
                    if (data.getBooleanExtra(Constant.EXTRA_TOPIC_DELETE, false)) {
                        resultsList.remove(i);
                        bottomTopicListV1.notifyItemRemove(i);
                        Marker remove = topicMarkerList.remove(i);
                        if (remove != null) {
                            remove.destroy();
                        }
                        lastSelectPosition = null;
//                        //删除maker
//                        for (int x = topicMarkerList.size() - 1; x >= 0; x--) {
//                            Marker marker = topicMarkerList.get(x);
//                            marker.getObject()
//                        }
                    } else if (data.getBooleanExtra(Constant.EXTRA_TOPIC_CHANGE, false)) {//主题改变，这个对应的可能很多，比如评论数量增加
                        resultsList.set(i, updateTopic);
                        bottomTopicListV1.notifyItemChange(i);
                    }
                    break;
                }
            }


        }
    }

    public void onTopicDetailActivityFinish(Intent data) {
        Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        if (updateTopic == null) {
            return;
        }
        for (int i = 0; i < resultsList.size(); i++) {
            Topic topic = resultsList.get(i);
            if (TextUtils.equals(updateTopic.getId(), topic.getId())) {
                resultsList.remove(i);
                resultsList.add(i, updateTopic);
                bottomTopicListV1.notifyItemChange(i);
                break;
            }
        }
    }

//    private void showGuide() {
//        Animation enterAnimation = new AlphaAnimation(0f, 1f);
//        enterAnimation.setDuration(800);
//        enterAnimation.setFillAfter(true);
//
//        Animation exitAnimation = new AlphaAnimation(1f, 0f);
//        exitAnimation.setDuration(600);
//        exitAnimation.setFillAfter(true);
//
//        //新增多页模式，即一个引导层显示多页引导内容
//        NewbieGuide.with(this)
//                .setLabel("mapFragment")//设置引导层标示区分不同引导层，必传！否则报错
////                .anchor(anchor)
//                .setOnGuideChangedListener(new OnGuideChangedListener() {
//                    @Override
//                    public void onShowed(Controller controller) {
//                        Log.e(TAG, "NewbieGuide onShowed: ");
//                        //引导层显示
//                    }
//
//                    @Override
//                    public void onRemoved(Controller controller) {
//                        Log.e(TAG, "NewbieGuide  onRemoved: ");
//                        //引导层消失（多页切换不会触发）
//                    }
//                })
//                .setOnPageChangedListener(new OnPageChangedListener() {
//
//                    @Override
//                    public void onPageChanged(int page) {
//                        //引导页切换，page为当前页位置，从0开始
//                        // Toast.makeText(getActivity(), "引导页切换：" + page, Toast.LENGTH_SHORT).show();
//                    }
//                })
//                //.alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
//                .addGuidePage(//添加一页引导页
//                        GuidePage.newInstance()//创建一个实例
//                                .addHighLight(ivSearch, HighLight.Shape.CIRCLE, 30)//添加高亮的view
////                                .addHighLight(tvBottom,
////                                        new RelativeGuide(R.layout.view_relative_guide, Gravity.TOP, 100) {
////                                            @Override
////                                            protected void offsetMargin(MarginInfo marginInfo, ViewGroup viewGroup, View view) {
////                                                marginInfo.leftMargin += 100;
////                                            }
////                                        })
//                                .setLayoutRes(R.layout.view_guide)//设置引导页布局
//                                .setEnterAnimation(enterAnimation)//进入动画
//                                .setExitAnimation(exitAnimation)//退出动画
//                )
//                .addGuidePage(GuidePage.newInstance()
//                                .addHighLight(btn_publish, HighLight.Shape.CIRCLE, 30)
//                                .setLayoutRes(R.layout.view_guide_to_publish, R.id.iv)//引导页布局，点击跳转下一页或者消失引导层的控件id
//                                .setOnLayoutInflatedListener(new OnLayoutInflatedListener() {
//                                    @Override
//                                    public void onLayoutInflated(View view, final Controller controller) {
////                                view.findViewById(R.id.textView).setOnClickListener(new View.OnClickListener() {
////                                    @Override
////                                    public void onClick(View v) {
////                                        controller.showPreviewPage();
////                                    }
////                                });
//                                    }
//                                })
//                                .setEverywhereCancelable(false)//是否点击任意地方跳转下一页或者消失引导层，默认true
//                                //.setBackgroundColor(getResources().getColor(R.color.transparent_black))//设置背景色，建议使用有透明度的颜色
//                                .setEnterAnimation(enterAnimation)//进入动画
//                                .setExitAnimation(exitAnimation)//退出动画
//                )
//                .addGuidePage(GuidePage.newInstance()
//                                .addHighLight(btn_topicList, HighLight.Shape.CIRCLE, 30)
//                                .setLayoutRes(R.layout.view_guide_to_topic_list, R.id.iv)//引导页布局，点击跳转下一页或者消失引导层的控件id
//                                .setOnLayoutInflatedListener(new OnLayoutInflatedListener() {
//                                    @Override
//                                    public void onLayoutInflated(View view, final Controller controller) {
////                                view.findViewById(R.id.textView).setOnClickListener(new View.OnClickListener() {
////                                    @Override
////                                    public void onClick(View v) {
////                                        controller.showPreviewPage();
////                                    }
////                                });
//                                    }
//                                })
//                                .setEverywhereCancelable(false)//是否点击任意地方跳转下一页或者消失引导层，默认true
//                                //.setBackgroundColor(getResources().getColor(R.color.transparent_black))//设置背景色，建议使用有透明度的颜色
//                                .setEnterAnimation(enterAnimation)//进入动画
//                                .setExitAnimation(exitAnimation)//退出动画
//                ).addGuidePage(GuidePage.newInstance()
//                        .addHighLight(btn_showContact, HighLight.Shape.CIRCLE, 30)
//                        .setLayoutRes(R.layout.view_guide_open_contact, R.id.iv)//引导页布局，点击跳转下一页或者消失引导层的控件id
//                        .setOnLayoutInflatedListener(new OnLayoutInflatedListener() {
//                            @Override
//                            public void onLayoutInflated(View view, final Controller controller) {
////                                view.findViewById(R.id.textView).setOnClickListener(new View.OnClickListener() {
////                                    @Override
////                                    public void onClick(View v) {
////                                        controller.showPreviewPage();
////                                    }
////                                });
//                            }
//                        })
//                        .setEverywhereCancelable(false)//是否点击任意地方跳转下一页或者消失引导层，默认true
//                        //.setBackgroundColor(getResources().getColor(R.color.transparent_black))//设置背景色，建议使用有透明度的颜色
//                        .setEnterAnimation(enterAnimation)//进入动画
//                        .setExitAnimation(exitAnimation)//退出动画
//        )
//
//                .show();//显示引导层(至少需要一页引导页才能显示)
//    }


}

